<!DOCTYPE html>
<html lang="en">
<div th:fragment="publish">
	<div class="modal fade" id="loadingModal">
		<div style="width: 200px; height: 20px; z-index: 20000; position: absolute; text-align: center; left: 50%; top: 50%; margin-left: -100px; margin-top: -10px">
			<div class="progress progress-striped active"
				style="margin-bottom: 0;">
				<div class="progress-bar" id="progress-bar" style="width: 100%;"></div>
			</div>
			<h5 style="color: black">
				<strong id="msg">正在发布，请稍等 ...</strong>
			</h5>
		</div>
	</div>
	<!-- <div class="page-container"> -->
	<form method="post" id="PublishFM" enctype="multipart/form-data">
		<div class="input-group" style="padding-top: 10px">
	      <span class="input-group-addon">名称：</span> 
	      <input type="text" class="form-control" name = "objName" id="objName" placeholder="产品名称">
	    </div>
	    <div class="divline"></div>
		<div class="input-group">
			<span class="input-group-addon">金额：</span> 
			<input type="text" class="form-control" name = "objPrice" id="objPrice" 
			onkeyup="this.value=/^\d+\.?\d{0,2}$/.test(this.value) ? this.value : this.value.substring(0,this.value.length-1)"
			placeholder="产品金额">
		</div>
		<div class="divline"></div>
		<div class="input-group">
			<span class="input-group-addon">描述：</span> 
			<textarea class="form-control"  rows="2" cols="200" name = "objDesc" id="objDesc" placeholder="产品描述"></textarea>
		</div>
		<div class="divline"></div>
		<div class="input-group">
			<span class="input-group-addon">类型：</span>
			<select class="form-control selectpicker" 
				data-live-search="true"
				name="objType" id="objType" multiple="multiple">
				<optgroup label="特定产品" th:label="${group.name}" th:each="group:${types}">
					<option value="100" th:value="${type.code}" th:text="${type.name}" th:each="type:${group.children}">特定产品</option>
				</optgroup>
			</select>
		</div>
		<div class="divline"></div>
		<div class="release_up_pic">
			<div class="up_pic">
				<span id="chose_pic_btn">
					<input type="file" name="files" id="files" accept="image/*" multiple="multiple"/>
				</span>
			</div>
			<br>
			<a type="button" class="btn btn-primary" id="submit" style="width: 100%">确认发布</a>
		</div>
	</form>
	<!-- </div> -->
	<script type="text/javascript">
	 	// 允许上传的图片类型  
	    var allowTypes = ['image/jpg', 'image/jpeg', 'image/png', 'image/gif'];
	    var picArr = new Array();// 存储图片
	    // 1024KB，也就是 10MB  
	    var maxSize = 1024 * 1024 * 10;
	    // 图片最大宽度  
	    var maxWidth = 300;
	    // 最大上传图片数量  
	    var maxCount = 7;
	    //初始化页面
		$(function() {
		    $('#files').on('change', function(event) {
		        var files = event.target.files;
		        var eachSize = files.length;
				var selected = $('.pic_look').length;//当前选择文件个数
		        // 如果没有选中文件，直接返回  
		        if (eachSize === 0) {
		            return;
		        }
		        //限制多选是只显示9个
				if (selected >= maxCount) {
	                alert('最多只能上传' + maxCount + '张图片');
	                return;
	            }
		        //执行到这里说明 selected < maxCount
		        if(selected < files.length){
		        	eachSize = files.length-selected;//添加次数为候补
		        }
		        //第一次选择个数大于9个则只添加前9个
		        if(eachSize > maxCount){
		        	eachSize = maxCount;
		        }
		        for (var i = 0; i < eachSize; i++) {
		            var file = files[i];
		            var reader = new FileReader();
	
		            // 如果类型不在允许的类型范围内  
		            if (allowTypes.indexOf(file.type) === -1) {
		                alert('该类型不允许上传');
		                continue;
		            }
	
		            if (file.size > maxSize) {
		                alert('图片太大，不允许上传');
		                continue;
		            }
		            
		            reader.onload = function(e) {
		                var img = new Image();
		                img.onload = function() {
		                    // 不要超出最大宽度  
		                    var w = Math.min(maxWidth, img.width);
		                    // 高度按比例计算  
		                    var h = img.height * (w / img.width);
		                    var canvas = document.createElement('canvas');
		                    var ctx = canvas.getContext('2d');
		                    // 设置 canvas 的宽度和高度  
		                    canvas.width = w;
		                    canvas.height = h;
		                    ctx.drawImage(img, 0, 0, w, h);
		                    var base64 = canvas.toDataURL('image/png');
		                    var _str = "<span class='pic_look' style='background-image: url("+ img.src + ")'><em id='delete_pic'>-&nbsp;</em></span>";
		                    $('#chose_pic_btn').before(_str);
		    				var _i =  picArr.length;
		    				picArr[_i] = base64;
		    				//console.log(picArr);
		                };
		                img.src = e.target.result;
		            };
		            reader.readAsDataURL(file);
		        }
		        // end for 
		    });
			 // 删除
			$(document).on('click', '#delete_pic', function(event) {
				var aa = $(this).parents(".pic_look").index();
				picArr.splice(aa,1);
				$(this).parents(".pic_look").remove();
				console.log(picArr);
			});	
			// 发布
			$(document).on('click', '#submit', function(event) {
				if(!$('#objName').val()){
					alert("名称不能为空");
					$('#objName').focus();
					return;
				}
				if(!$('#objPrice').val()){
					alert("价格不能为空");
					$('#objPrice').focus();
					return;
				}
				if(!$('#objDesc').val()){
					alert("描述不能为空");
					$('#objDesc').focus();
					return;
				}
				if(!$('#objType').val()){
					alert("请至少选择一个类型");
					$('#objType').focus();
					return;
				}
				var files = document.getElementById("files").files;
				if(!files || files.length < 1){
					alert("请至少选择一张图片");
					return ;
				}
				sumitData();
			});
		});
	    function sumitData(){
	    	$("#loadingModal").modal('show');
			//Ajax 提交
            var formData = new FormData();
            formData.append("objName",$('#objName').val());
            formData.append("objPrice",$('#objPrice').val());
            formData.append("objDesc",$('#objDesc').val());
            formData.append("objType",$('#objType').val());
            //formData.append("userInfo","");
            //console.log("选中类型："+$('#objType').val());
            var files = document.getElementById("files").files;
            for(var i=0; i < files.length; i++){
          		console.log("正在加载文件："+files[i].name);
          	  	formData.append("files",files[i]);   // 文件对象
          	}
            var url = "http://www.godbirds.net:8888/flowers/publish/upload.do";
           	$.ajax({
                type: 'post',
                url: url,
                data: formData,
                dataType:'json',
                cache: false,
                /**
                 *必须false才会自动加上正确的Content-Type
                 */
                contentType: false,
                 /**
                 * 必须false才会避开jQuery对 formdata 的默认处理
                 * XMLHttpRequest会对 formdata 进行正确的处理
                 */
                processData: false,
                success:function(data){
                	$('#msg').html(data.retmsg);
                    $('#loadingModal').modal('hide');
                    alert(data.retmsg);
                },
                error: function (){
                	$('#msg').html="发布失败";
                    $('#loadingModal').modal('hide');
                    alert("发布失败");
                }
            });
	    }
	</script>
</div>
</html>